﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace DNA.Mvc.Exporting
{
    /// <summary>
    /// Present a packing container object, use to create data, template and files to installable package.
    /// </summary>
    public class ExporterContainer : CommandContainer<Exporter,ExporterFilter>
    {
        //private IExporterFactory factory;
        
        //public IExporterFactory Source
        //{
        //    get { return factory; }
        //    private set { factory = value; }
        //}

        //public ExporterContainer(IExporterFactory sourceFactory)
        //{
        //    factory = sourceFactory;
        //}

        public ExporterContainer() { }

        public ExporterContainer(IEnumerable<Exporter> exporters) 
        {
            this.InnerItems.Clear();
            this.InnerItems.AddRange(exporters); 
        }

        /// <summary>
        /// Gets the registed exports.
        /// </summary>
        public virtual ICollection<Exporter> Exporerts
        {
            get
            {
                return InnerItems;
            }
        }

        /// <summary>
        /// Execute all registed exporting task and save the files to destination directory
        /// </summary>
        /// <param name="destination">The directiory where contains the exporting results.</param>
        public void Process(string destination,object contextData,HttpContextBase httpContext=null)
        {
            var context = new ExportingContext(contextData);
            context.Destination=destination;
            context.HttpContext = httpContext == null ? (new HttpContextWrapper(HttpContext.Current)) : httpContext;
            Invoke(context);

            if (context.Installers.Count > 0)
                System.IO.File.WriteAllText(destination + (destination.EndsWith("\\") ? "" : "\\") + "install.xml", GetInstallerManifest(context));
        }

        private string GetInstallerManifest(ExportingContext context)
        {
            var xmlBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            xmlBuilder.Append("<installers>");
            foreach (var key in context.Installers.Keys)
            {
                xmlBuilder.AppendFormat("<installer name=\"{0}\" >", key);
                if (!string.IsNullOrEmpty(context.Installers[key]))
                    xmlBuilder.Append(context.Installers[key]);
                xmlBuilder.Append("</installer>");
            }
            xmlBuilder.Append("</installers>");
            return xmlBuilder.ToString();
        }
    }
}
